package com.hgvip.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by arnold.zhu on 2017/9/20.
 */
@Service
public class KaoLaService {

    private Logger logger = LoggerFactory.getLogger(KaoLaService.class);

    @Autowired
    private GoodsService goodsService;

    public String syncAllGoods() {
        String ids = goodsService.queryAllGoodsId();
        JSONObject jsonObject = JSON.parseObject(ids);
        List<String> idList = (List<String>) jsonObject.get("goodsInfo");
        // 开启一定数量的线程去获取商品信息
        int count = idList.size() % 20 == 0 ? idList.size() / 20 : idList.size() / 20 + 1;
        CountDownLatch latch = new CountDownLatch(count - 1);
        ExecutorService executorService = Executors.newFixedThreadPool(20);
        for (int i = 0; i < count; i++) {
            List<String> skuIds = new ArrayList<>();
            // 每次最多20个skuId
            for (int j = i * 20; j < (i + 1) * 20 - 1 && j < idList.size() - 1; j++) {
                skuIds.add(idList.get(j));
            }
            executorService.execute(() -> {
                String goodsInfo = goodsService.queryGoodsInfoByIds(JSON.toJSONString(skuIds), "0", "");
                logger.info("当前批次商品信息:" + goodsInfo);
                // insert db

                latch.countDown();
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

}
